<?php
namespace App\Http\Controllers\AppApi\Member;

use App\Jobs\Fun;
use App\Models\Admin\YzmModel;
use App\Models\AreaModel;
use App\Services\Admin\UserService;
use App\Utilities\Sms;
use App\Utilities\Upload;
use App\Utilities\Utility;
use Illuminate\Http\Request;
use Hash;

class LoginController extends BaseController
{
    /**
     * 登陆注册
     * 制作者：九哥
     */

    protected $userService;

    public function __construct()
    {
        parent::__construct();
        $this->userService = new UserService();
    }

    /**
     * 登陆
     */
    public function doLogin(Request $request)
    {
        $phone = $request->phone;
        $pwd = $request->pwd;
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        if (!preg_match('/^1[34578]\d{9}$/',$phone)) {
            return $this->toJson(-8);
        }
        $model = $this->userService->getOneByMobile($phone);
        if (!$model) { return $this->toJson(-9); }
        if (!(Hash::check($pwd,$model->password))) {
            return $this->toJson(-10);
        }
        $token = $this->accessSet($model->id);
        $cate = $this->userService
            ->getUserType($model->id,$model->type);
        $resArr = array(
            'token' => $token,
            'type' => $model->type,
            'cate' => $cate,
        );
        return $this->toJson(0,$resArr);
    }

    /**
     * 注册
     */
    public function doRegist(Request $request)
    {
        $phone = $request->phone;
        $pwd = $request->pwd;
        $yzm = $request->yzm;
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        if (!$phone || !$pwd || !$yzm) {
            return $this->toJson(-2);
        }
        //验证码校验
        $resYzm = $this->getYzm($phone);
        if (!$resYzm) { return $this->toJson(-7); }
        if (!preg_match('/^1[345678]\d{9}$/',$phone)) {
            return $this->toJson(-8);
        }
        if (!preg_match('/^[0-9a-zA-Z_]{5,20}$/',$pwd)) {
            return $this->toJson(-12);
        }
        $model = $this->userService->getOneByMobile($phone);
        if ($model) { return $this->toJson(-4); }
        //保存信息
        $nameStr = '用户'.date('YmdHis',time()).rand(1000,9999);
        $pwdHash = Hash::make($pwd);
        $dataArr = array(
            'name' => $nameStr,
            'phone' => $phone,
            'password' => $pwdHash,
        );
        $lastId = $this->userService->add($dataArr);
        //生成token
        $token = $this->accessSet($lastId);
        $resArr = array(
            'token' => $token,
            'type' => 0,
            'cate' => 0,
        );
        //记录用户须知
        $this->userService->setUserNotice($lastId);
        return $this->toJson(0,$resArr);
    }

    /**
     * 发送验证码
     */
    public function sendYzm(Request $request)
    {
        return $this->toJson(0); //先屏蔽验证码
        $phone = $request->phone;
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        if (!preg_match('/^1[34578]\d{9}$/',$phone)) {
            return $this->toJson(-8);
        }
        $resYzm = $this->getYzm($phone);
        if ($resYzm) { return $this->toJson(-6); }
//        $code = Utility::getRandStr(rand(4,6),0);
        $code = Utility::getRandStr(4,0);
        $dataArr = array(
            'phone' => $phone,
            'code' => $code,
            'created_at' => time(),
        );
       $lastId = YzmModel::insertGetId($dataArr);
        $sms = new Sms();
        $msg = "【美策】验证码{$code}，您正在进行美策平台的账号注册，有效时间30分钟身份验证，打死不要告诉别人哦！";
        $resSms = $sms->sendSMS($phone, $msg);
        $resSms = json_decode($resSms, true);
        if (empty($resSms) || !empty($resSms['errorMsg'])) {
            return $this->toJson(-11);
        }
        YzmModel::where('id',$lastId)->update(array('status'=>2));
        return $this->toJson(0);
    }

    /**
     * 密码重置
     */
    public function setPwd(Request $request)
    {
        $phone = $request->phone;
        $pwd = $request->pwd;
        $yzm = $request->yzm;
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        if (!$phone || !$pwd || !$yzm) {
            return $this->toJson(-2);
        }
//        //验证码校验
//        $resYzm = $this->getYzm($phone);
//        if (!$resYzm) { return $this->toJson(-7); }
        if (!preg_match('/^1[34578]\d{9}$/',$phone)) {
            return $this->toJson(-8);
        }
        if (!preg_match('/^[0-9a-zA-Z_]{5,20}$/',$pwd)) {
            return $this->toJson(-12);
        }
        $model = $this->userService->getOneByMobile($phone);
        if (!$model) { return $this->toJson(-9); }
        $this->userService->setPwdByMobile($phone,Hash::make($pwd));
        return $this->toJson(0);
    }

    /**
     * 设置主体身份
     */
    public function setIndentity(Request $request)
    {
        $token = $request->token;
        $type = $request->type;
        $typeInfo = $request->typeInfo;
        $introducer = $request->introducer;
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        //更新用户信息
        $userArr = array(
            'type' => $type,
            'introducer' => $introducer ? $introducer : '',
        );
        $this->userService->setType($uid,$userArr);
        return $this->toJson(0);
    }

    /**
     * 获取生日的天
     */
    public function getBirthDay(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $month = $request->month;
        if ($month<1 || $month>12) { return $this->toJson(-2); }
        $dayStr = '';
        if ($month==2) {
            for ($i=1;$i<=28;$i++) {
                if ($i<10) { $i = '0'.$i; }
                $dayStr .= '<option value="'.$i.'">'.$i.'</option>';
            }
        } else if (in_array($month,[1,3,5,7,8,10,12])) {
            for ($i=1;$i<=31;$i++) {
                if ($i<10) { $i = '0'.$i; }
                $dayStr .= '<option value="'.$i.'">'.$i.'</option>';
            }
        } else {
            for ($i=1;$i<=30;$i++) {
                if ($i<10) { $i = '0'.$i; }
                $dayStr .= '<option value="'.$i.'">'.$i.'</option>';
            }
        }
        return $this->toJson(0,$dayStr);
    }

    /**
     * 获取验证码
     */
    public function getYzm($phone)
    {
        return true; //先取消验证码验证
//        $start = strtotime(date('Ymd').'000000');
//        $end = strtotime(date('Ymd').'235959');
        $model = YzmModel::where('phone',$phone)
            ->where('status',2)
//            ->where('created_at','>',$start)
//            ->where('created_at','<=',$end)
            ->where('created_at','>',time()-60*30)
            ->first();
        return $model ? $model->code : '';
    }

    /**
     * 获取地区
     */
    public function getRegions(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $pid = $request->pid;
        $models = AreaModel::where('pid',$pid)->get();
        $dataArr = array();
        if (!count($models)) { return $this->toJson(-3); }
        foreach ($models as $k=>$model) {
            $dataArr[$k]['id'] = $model->id;
            $dataArr[$k]['name'] = $model->name;
        }
        return $this->toJson(0,$dataArr);
    }

    /**
     * IOS用，判断H5
     */
    public function isH5ByIos(Request $request)
    {
        return $this->toJson(0,array('ios'=>1));
    }

    /**
     * 图片上传通用方法
     * /api/member/upload/img
     */
    public function setUploadImg(Request $request)
    {


        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        if (!isset($request->img)) {
            return $this->toJson(-17);
        }
        $resImg = Upload::uploadImgByApi($request,'img');

        if ($resImg['code']!=0) { return $this->toJson(-23); }
        $img = $resImg['filePath'];
        $dataArr = array(
            'uid' => $uid,
            'url' =>$img,
            'created_at' => time(),
        );
        $this->userService->setImgTmp($dataArr);
        ///print_r($resImg);exit;
        return $this->toJson(0,array(
            'img'=>Fun::pImg($img),
            'big'=>Fun::pImg($resImg['big'])
        ));
    }

    /**
     * 用户须知
     */
    public function setUserNotice(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $this->userService->setUserNotice($uid);
        return $this->toJson(0);
    }
}